﻿@using BlazorLearnWebApp.Entity
@using System.Diagnostics.CodeAnalysis


@implements IResultDialog

@* @if(RoleEntity == null)
{
    <span>Loading...</span>
}
else
{
    @RoleEntity.RoleName
} *@

<TreeView TItem="MenuEntity" Items="Items" ShowCheckbox="true" AutoCheckChildren="true" AutoCheckParent="true" ShowIcon="true">

</TreeView>

@code {
    private List<TreeViewItem<MenuEntity>> Items { get; set; } = new List<TreeViewItem<MenuEntity>>();

    [Parameter]
    public int RoleId { get; set; }


    private RoleEntity? RoleEntity{ get; set; }

    protected override async Task OnInitializedAsync()
    {
        RoleEntity = await RoleEntity.Where(x => x.Id == RoleId).IncludeMany(x => x.Menus).FirstAsync();

        await base.OnInitializedAsync();
        await RefreshItems();
    }


    private async Task RefreshItems()
    {
        Items.Clear();
        var menus = await MenuEntity.Select.ToListAsync();
        Items.AddRange(CascadingMenu(menus, null));
    }


    private List<TreeViewItem<MenuEntity>> CascadingMenu(List<MenuEntity> menuEntities, TreeViewItem<MenuEntity> parent) => menuEntities
    .Where(x => x.ParentId == (parent?.Value.Id ?? 0))
    .Select(x =>
    {
        var treeViewItem = new TreeViewItem<MenuEntity>(x) { Text = x.MenuName, Icon = x.Icon, IsExpand = true, Parent = parent };
        treeViewItem.Items = CascadingMenu(menuEntities, treeViewItem);
        if(RoleEntity?.Menus?.Any(y=>y.Id == x.Id)==true)
        {
            treeViewItem.CheckedState = CheckboxState.Checked;
        }

        return treeViewItem;
    })
    .ToList();


    public async Task OnClose(DialogResult result)
    {
        if(result== DialogResult.Yes)
        {
            var menus = new List<MenuEntity>();
            GetMenus(Items.Where(x => x.CheckedState != CheckboxState.UnChecked), menus);
            RoleEntity!.Menus = menus;
            await RoleEntity.SaveManyAsync(nameof(RoleEntity.Menus));
        }
    }

    /// <summary>
    /// 递归获取菜单
    /// </summary>
    /// <param name="treeViewItems"></param>
    /// <param name="menuEntities"></param>
    private void GetMenus(IEnumerable<TreeViewItem<MenuEntity>> treeViewItems,List<MenuEntity> menuEntities)
    {
        menuEntities.AddRange(treeViewItems.Select(x => x.Value));
        foreach (var treeViewItem in treeViewItems)
        {
            if(treeViewItem.Items.Any(x=>x.CheckedState!=CheckboxState.UnChecked))
            {
                GetMenus(treeViewItem.Items.Where(x => x.CheckedState != CheckboxState.UnChecked), menuEntities);
            }
        }
    }
}
